<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 产品分类下拉树 -->
      <el-col :lg="4" :xs="24">
        <el-card shadow="hover">
          <div class="flex items-center justify-between mb-2">
          <el-input v-model="categoryName" placeholder="请输入产品分类名" prefix-icon="Search" clearable />
       <!--  这个是以路由方式跳转到产品分类页
          <el-button 
              type="primary" 
              size="small" 
              icon="Plus" 
              @click="addCategory"
              v-hasPermi="['basedata:category:add']"
            /> -->

            <el-button 
              type="primary" 
              size="small" 
              icon="Plus" 
              @click="showCategoryDialog = true"
              v-hasPermi="['basedata:category:add']"
            />
            </div> 
          <el-tree
            ref="categoryTreeRef"
            class="mt-2"
            node-key="id"
            :data="categoryOptions"
            :props="{ label: 'name', children: 'children' } as any"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          ></el-tree>
        </el-card>
      </el-col>
      <!-- 产品列表 -->
      <el-col :lg="20" :xs="24">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
       <!--      <el-form-item label="产品大类ID" prop="productCategoryId">
              <el-input v-model="queryParams.productCategoryId" placeholder="请输入产品大类ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="产品大类名称" prop="productCategoryName">
              <el-input v-model="queryParams.productCategoryName" placeholder="请输入产品大类名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="材料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入材料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basedata:prodinfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['basedata:prodinfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['basedata:prodinfo:remove']">删除</el-button>
          </el-col>
       <!--    <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['basedata:prodinfo:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="prodinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品唯一标识" align="center" prop="id" v-if="false" />
        <el-table-column label="产品大类ID" align="center" prop="productCategoryId"  v-if="false" />
        <el-table-column label="产品大类名称" align="center" prop="productCategoryName" />
        <el-table-column label="材料名称" align="center" prop="materialName" />
        <el-table-column label="规格型号" align="center" prop="specificationModel" />
        <el-table-column label="材质" align="center" prop="materialType" />
        <el-table-column label="单位" align="center" prop="unit">
          <template #default="scope">
            <dict-tag :options="data_product_unit" :value="scope.row.unit"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column label="单重" align="center" prop="singleWeight" />
        <el-table-column label="总重" align="center" prop="totalWeight" />
        <el-table-column label="结构属性" align="center" prop="structuralAttributes" />
        <el-table-column label="制造工艺" align="center" prop="manufacturingProcess" />
        <el-table-column label="是否外协或外购" align="center" prop="isOutsourced">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isOutsourced"/>
          </template>
        </el-table-column>
        <el-table-column label="检验或试验" align="center" prop="inspectionOrTesting" />
        <el-table-column label="相关标准" align="center" prop="relevantStandards" />
        <el-table-column label="产品图片" align="center" prop="productImageUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.productImageUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="创建单位" align="center" prop="createDept"  v-if="false" />
        <el-table-column label="创建人" align="center" prop="createdBy" v-if="false" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['basedata:prodinfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['basedata:prodinfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改产品信息维护对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="prodinfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="产品分类" prop="productCategoryId"  v-show="false">
          <el-input v-model="form.productCategoryId" placeholder="请选择产品分类" />
        </el-form-item>
        
          <el-form-item label="产品分类" prop="productCategoryId">
              <el-tree-select
                  v-model="form.productCategoryId"
                :data="categoryOptions"
                :props="{ value: 'id', label: 'name', children: 'children' } as any"
                value-key="id"
                placeholder="请选择产品分类"
                check-strictly
                @node-click="handleCategoryChange" 
              />
            </el-form-item>
        <el-form-item label="产品大类名称" prop="productCategoryName"  v-if="false">
          <el-input v-model="form.productCategoryName" placeholder="请输入产品大类名称" />
        </el-form-item> 
        <el-form-item label="材料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specificationModel">
          <el-input v-model="form.specificationModel" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="材质" prop="materialType">
          <el-input v-model="form.materialType" placeholder="请输入材质" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位">
            <el-option
                v-for="dict in data_product_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单重" prop="singleWeight">
          <el-input v-model="form.singleWeight" placeholder="请输入单重" />
        </el-form-item>
        <el-form-item label="总重" prop="totalWeight">
          <el-input v-model="form.totalWeight" placeholder="请输入总重" />
        </el-form-item>
        <el-form-item label="结构属性" prop="structuralAttributes">
          <el-input v-model="form.structuralAttributes" placeholder="请输入结构属性" />
        </el-form-item>
        <el-form-item label="制造工艺" prop="manufacturingProcess">
          <el-input v-model="form.manufacturingProcess" placeholder="请输入制造工艺" />
        </el-form-item>
        <el-form-item label="外协或外购" prop="isOutsourced">
          <el-select v-model="form.isOutsourced" placeholder="请选择是否外协或外购">
            <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验或试验" prop="inspectionOrTesting">
          <el-input v-model="form.inspectionOrTesting" placeholder="请输入检验或试验" />
        </el-form-item>
        <el-form-item label="相关标准" prop="relevantStandards">
            <el-input v-model="form.relevantStandards" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="产品图片" prop="productImage">
          <image-upload v-model="form.productImage"/>
        </el-form-item>
  <!--       <el-form-item label="创建单位" prop="createDept">
          <el-input v-model="form.createDept" placeholder="请输入创建单位" />
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </el-col>
  </el-row>

    <!-- 产品分类新增对话框 -->
    <el-dialog 
      :visible.sync="showCategoryDialog" 
      title="新增产品分类" 
      width="40%"
      append-to-body
    >
      <CategoryIndex 
        :action="'add'" 
        :parentId="selectedCategory?.id" 
        @success="handleCategorySuccess"
      />
      <template #footer>
        <el-button @click="showCategoryDialog = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Prodinfo" lang="ts">
import { listProdinfo, getProdinfo, delProdinfo, addProdinfo, updateProdinfo } from '@/api/basedata/prodinfo';
import { ProdinfoVO, ProdinfoQuery, ProdinfoForm } from '@/api/basedata/prodinfo/types';

//弄下拉樹所引入的东西
import { ref, reactive, onMounted } from 'vue';
import { listCategory } from '@/api/basedata/category'; // 获取产品分类的 API
import { CategoryVO } from '@/api/basedata/category/types';


//因小加号而导入的东西
import { useRouter } from 'vue-router';
import CategoryIndex from '@/views/basedata/category/index.vue'; // 为了新增而引入产品分类组件

const showCategoryDialog = ref(false);
const dialogAction = ref('add');

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, data_product_unit } = toRefs<any>(proxy?.useDict('sys_yes_no', 'data_product_unit'));

const categoryName = ref('');
const categoryOptions = ref<CategoryVO[]>([]);//树的内容

const prodinfoList = ref<ProdinfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const prodinfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProdinfoForm = {
  id: undefined,
  productCategoryId: undefined,
  productCategoryName: undefined,
  materialName: undefined,
  specificationModel: undefined,
  materialType: undefined,
  unit: undefined,
  quantity: undefined,
  singleWeight: undefined,
  totalWeight: undefined,
  structuralAttributes: undefined,
  manufacturingProcess: undefined,
  isOutsourced: undefined,
  inspectionOrTesting: undefined,
  relevantStandards: undefined,
  productImage: undefined,
  createDept: undefined,
  createBy: undefined,
  createTime: undefined,
}
const data = reactive<PageData<ProdinfoForm, ProdinfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCategoryId: undefined,
    productCategoryName: undefined,
    materialName: undefined,
    productImage: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "产品唯一标识不能为空", trigger: "blur" }
    ],
    productCategoryId: [
      { required: true, message: "产品大类ID不能为空", trigger: "blur" }
    ],
    materialName: [
      { required: true, message: "材料名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品信息维护列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProdinfo(queryParams.value);
  prodinfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/**下拉树相关 */
/** 查询产品分类下拉树结构 */
 const getTreeselect = async () => {
  const res = await listCategory();
  categoryOptions.value = [];

  console.log('分类数据1111111111111:', res.data); // 检查这里是否有数据
  // 处理树形数据
  const data = proxy?.handleTree<CategoryVO>(res.data, 'id', 'parentId');
  if (data) {
    categoryOptions.value = data; // 将处理后的树形数据赋值
  }
}; 
/** 查询产品分类下拉树结构 */
/* const getTreeselect = async () => {
  debugger;
  const res = await listCategory();
  console.log('分类数据:', res.rows); // 新增：打印后端返回的数据，用于调试
  
  // 假设后端返回的数据已经是树形结构，直接赋值
  if (res.rows) {
    categoryOptions.value = res.rows; // 新增：直接使用后端返回的树形数据
  }
}; */


// 保存选中的产品大类节点信息
const selectedCategory = ref<CategoryVO | null>(null);
/** 下拉树节点点击事件 */
const handleNodeClick = (node: CategoryVO) => {


  queryParams.value.productCategoryId = node.id;
  selectedCategory.value = node; // 保存选中的节点信息
  getList();
};

/** 过滤下拉树节点 */
const filterNode = (value: string, data: CategoryVO) => {
  if (!value) return true;
  return data.name.includes(value);
};

onMounted(() => {
  getTreeselect();
  getList();
});

//新建产品界面的下拉树事件

const handleCategoryChange = (data) => {
  if (data) {
    // 更新表单中的分类名称（可选）
    form.value.productCategoryName = data.name;
  } else {
    form.value.productCategoryName = '';
  }
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  prodinfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProdinfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加产品信息维护";
  if (selectedCategory.value) {
    form.value.productCategoryId = selectedCategory.value.id;
    form.value.productCategoryName = selectedCategory.value.name;
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ProdinfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getProdinfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改产品信息维护";
}

/** 提交按钮 */
const submitForm = () => {
  prodinfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProdinfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addProdinfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProdinfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品信息维护编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delProdinfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basedata/prodinfo/export', {
    ...queryParams.value
  }, `prodinfo_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});


/** 点击小加号，弹出添加产品分类 ，这是路由方式跳转，先废弃*/
const addCategory = () => {
  router.push({
    name: 'category',
    query: { action: 'add' }
  });
};


/** 处理产品分类新增成功事件 */
const handleCategorySuccess = () => {
  showCategoryDialog.value = false;
  proxy?.$modal.msgSuccess('产品分类新增成功');
  getTreeselect(); // 刷新分类树
};

</script>
